//  配置
var _config = {
  //  base: 'http://t.imaisu.com',
  base: '',
  getCapatha: '/api/captcha',
  sendSMS: '',
  login: '/api/login'
}

//  业务逻辑
var _main = {
  data: {

  },
  objs: {

  },
  //  点登录
  submit: function() {
    if ( !this.objs.code.value || !this.objs.mobile.value ){
      alert("请输入手机号和短信验证码")
      return false
    }
    let _params = {
      "code": this.objs.code.value,
    	"phone": this.objs.mobile.value
    }
    _utils.get(_config.login, _params, (res) => {
      console.log(res)
      if(!res || res.code == 200 ) {
        _utils.setCookie('usr',  _params.phone);
        window.location.href = "create.html"
      } else {
        alert(res.msg)
        this.refreshCapatha();
      }
    })
  },
  bindEvents: function () {
    this.objs.capatha.addEventListener('click', this.refreshCapatha.bind(this));
    this.objs.sendBtn.addEventListener('click', this.sendSMS.bind(this));
    this.objs.loginBtn.addEventListener('click', this.submit.bind(this));
  },
  refreshCapatha: function () {
    _utils.get(_config.getCapatha, {
    }, (res) => {
      console.log(res)
      this.objs.capatha.src = _config.base + '/admin/captcha/' + res.file;
      this.data.key = res.file;
    })
  },
  sendSMS: function () {
    if ( !this.objs.useInput.value || !this.objs.mobile.value ){
      alert("请输入手机号和验证码来获取短信")
      return false
    }
    _utils.post(_config.getCapatha, {
      "key": this.data.key,
    	"user_input": this.objs.useInput.value,
    	"mobile": this.objs.mobile.value
    }, (res) => {
      if (res.code == 200) {
        alert("发送成功")
      } else {
        alert(res.msg)
        this.refreshCapatha();
      }
    })
  },
  getObj: function () {
    this.objs.mobile = document.getElementById('mobile');
    this.objs.useInput = document.getElementById('user_input');
    this.objs.sendBtn = document.getElementById('sendBtn');
    this.objs.code = document.getElementById('code');
    this.objs.loginBtn = document.getElementById('loginBtn');
    this.objs.capatha = document.getElementById('capatha');
  },
  //  获取初始化数据\
  getInitData: function () {
    this.refreshCapatha();
  },
  init: function () {
    this.getInitData();
    this.getObj();
    this.bindEvents();
  }
}
//  run
_main.init();
